package com.business_clean.app.uitl.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.callback.GetUrlCacheBitmapListenerWithFail;
import com.business_clean.app.config.Constant;
import com.business_clean.app.uitl.GlideUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.util.Objects;

public class ShareHelperTools {

    private static IWXAPI api;

    private static ShareHelperTools instance;
    private static int stringId;

    private int WX_THUMB_SIZE = 300;
    // 微信图片kb 缩略图
    private int IMAGE_32_SIZE = 32 * 1024;//32kb
    private int IMAGE_128_SIZE = 128 * 1024;// 128KB

    private static final int TITLE_SIZE = 512;  //title限制长度不超过512Bytes
    private static final int DESCRIPTION_SIZE = 1024;  //description限制长度不超过1K
    private static final int TEXT_CONTENT_SIZE = 10 * 1024;  //纯文本分享文本内容限制长度不超过10K

    /**
     * 注册微信监听
     */
    public ShareHelperTools() {
        api = WXAPIFactory.createWXAPI(App.instance.getBaseContext(), Constant.WECHAT_APP_ID, true);
        api.registerApp(Constant.WECHAT_APP_ID);
    }

    public static ShareHelperTools getInstance() {
        if (instance == null) {
            synchronized (ShareHelperTools.class) {
                if (instance == null) {
                    instance = new ShareHelperTools();
                }
            }
        }
        return instance;
    }

    public IWXAPI getApi() {
        return api;
    }

    /**
     * 分享文本
     */
    public void shareText(ShareParams params, Activity activity) {
        if (params.getShareType() == ShareType.SMS) {
            shareSmsText(params.getTitle(), activity);
        } else {
            shareWxText(params, activity);
        }
    }

    private void shareWxText(ShareParams params, Activity mActivity) {

        WXTextObject textObj = new WXTextObject();

        //微信限制文字10K
        textObj.text = getLimitString(params.getDescription(), TEXT_CONTENT_SIZE);

        //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        msg.description = getLimitString(params.getDescription(), TEXT_CONTENT_SIZE);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.message = msg;
        if (params.getShareType() == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    private String getLimitString(String description, long size) {
        if (TextUtils.isEmpty(description)) {
            return "";
        }
        if (description.getBytes().length > size) {
            String substring = description.substring(0, description.length() - 1);
            return getLimitString(substring, size);
        } else {
            return description;
        }
    }

    /**
     * 分享Image
     */
    public void shareImage(ShareParams params, Activity mActivity) {
        checkShareChannel(params, 1, mActivity);
    }

    /**
     * 分享链接卡片
     */
    public void shareCardLink(ShareParams params, Activity mActivity) {
        checkShareChannel(params, 2, mActivity);
    }

    public void shareFileToWx(ShareParams params, Activity mActivity) {
        finalShareFile(params, mActivity);
    }

    /**
     * 检查一波那个渠道的，判断归一
     *
     * @param params
     * @param channel
     */
    private void checkShareChannel(ShareParams params, int channel, Activity mActivity) {
        if (mActivity == null) {
            //分享资源有误
            ToastUtils.showShort("分享资源有误");
            return;
        }
        Bitmap thumbBit = null;
        if (params.getBitmap() instanceof Bitmap) {
            thumbBit = (Bitmap) params.getBitmap();
        } else if (params.getBitmap() instanceof String) {
            GlideUtil.getUrlCacheBitmapForShareThumbnail(mActivity, params.getBitmap().toString(), new GetUrlCacheBitmapListenerWithFail() {
                @Override
                public void loadBitmap(Bitmap resource) {
                    if (channel == 1) {
                        finalShareImage(params, resource, mActivity);
                    } else if (channel == 2) {
                        finalWeChatWebLink(params, resource, mActivity);
                    }
                }

                @Override
                public void loadFail() {
                }
            });
        } else if (params.getBitmap() instanceof Integer) {
            thumbBit = ((BitmapDrawable) Objects.requireNonNull(ContextCompat.getDrawable(mActivity, ((int) params.getBitmap())))).getBitmap();
        } else {
            thumbBit = ((BitmapDrawable) Objects.requireNonNull(ContextCompat.getDrawable(mActivity, R.mipmap.icon_base_placeholder))).getBitmap();
        }
        if (params.getBitmap() instanceof String) {

        } else {
            if (channel == 1) {
                finalShareImage(params, thumbBit, mActivity);
            } else if (channel == 2) {
                finalWeChatWebLink(params, thumbBit, mActivity);
            }
        }
    }

    /**
     * 图片分享
     *
     * @param params
     * @param thumbBit
     */
    private void finalShareImage(ShareParams params, Bitmap thumbBit, Activity mActivity) {
        if (thumbBit == null) {
            ToastUtil.show("分享封面图不能为空");
            return;
        }

        WXImageObject imgObj = new WXImageObject();

        //判断图片是否大于1MB
        imgObj.imageData = SocialBitmapUtils.INSTANCE.compressToSize(thumbBit, IMAGE_128_SIZE);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.title = getLimitString(params.getTitle(), TITLE_SIZE);


        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        if (params.getShareType() == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }


    private void finalShareFile(ShareParams params, Activity mActivity) {
        WXFileObject fileObject = new WXFileObject();

        //判断图片是否大于10MB
        fileObject.filePath = params.getLinkUrl();

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = fileObject;
        msg.title = getLimitString(params.getTitle(), TITLE_SIZE);


        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message = msg;
        if (params.getShareType() == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }


    /**
     * web链接分享
     */
    private void finalWeChatWebLink(ShareParams params, Bitmap thumbBit, Activity mActivity) {
        if (thumbBit == null) {
            ToastUtil.show("分享封面图不能为空");
            return;
        }
        if (params.getShareType() == ShareType.SMS) {// 如果是分享短信出去，那么就直接return出去
            shareSmsText(params.getDescription(), mActivity);
            return;
        }
        if (params.getShareType() == ShareType.WWEIXIN) {//如果是企业微信
            shareToSystemText(params.getmWWeiXinDescription(), mActivity);
            return;
        }

        //链接长度需要小于10k
        if (!TextUtils.isEmpty(params.getLinkUrl())) {
            if (params.getLinkUrl().getBytes().length >= 10 * 1024) {
                ToastUtil.show("分享的链接太长");
                return;
            }
        }


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        WXWebpageObject webPageObject = new WXWebpageObject();

        webPageObject.webpageUrl = params.getLinkUrl();

        WXMediaMessage msg = new WXMediaMessage(webPageObject);
        req.transaction = buildTransaction("webpage");

        msg.title = getLimitString(params.getTitle(), TITLE_SIZE);
        msg.description = getLimitString(params.getDescription(), DESCRIPTION_SIZE);

//        msg.thumbData = parseBitmapToBytes(thumbBit, false);
        msg.thumbData = SocialBitmapUtils.INSTANCE.getStaticSizeBitmapByteByPath(thumbBit, IMAGE_32_SIZE);

        req.message = msg;
        if (params.getShareType() == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        api.sendReq(req);
    }

    /**
     * 最终小程序分享
     */
    private void finalWeChatMini(ShareMiniWeChatParams mMiniWeChatParams, Bitmap bitmap, Activity mActivity) {
        if (bitmap == null) {
            ToastUtil.show("分享封面图不能为空");
            return;
        }


        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = Constant.WECHAT_APP_ID; // 兼容低版本的网页链接

        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2

        miniProgramObj.userName = mMiniWeChatParams.getMiniUserId();     // 小程序原始id
        miniProgramObj.path = mMiniWeChatParams.getMiniPage();            //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);

        msg.title = getLimitString(mMiniWeChatParams.getMiniTitle(), TITLE_SIZE);
        msg.description = getLimitString(mMiniWeChatParams.getMiniDescription(), DESCRIPTION_SIZE);

        //小程序的图不能超过128kb ，防止图片太长或者太短，都处理一下，创建一个新的
//        msg.thumbData = parseBitmapToBytes(bitmap, true);
        msg.thumbData = SocialBitmapUtils.INSTANCE.getStaticSizeBitmapByteByPath(bitmap, IMAGE_128_SIZE);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("miniProgram");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
        api.sendReq(req);
    }

    /**
     * 分享小程序
     */
    public void shareMiniWeChat(ShareMiniWeChatParams mMiniWeChatParams, Activity mActivity) {
        if (mActivity == null) {
            ToastUtil.show("分享资源有误");
            return;
        }
        Bitmap bitmap = null;
        // 小程序消息封面图片，小于128k
        if (mMiniWeChatParams.getMiniThumb() instanceof Bitmap) {
            bitmap = (Bitmap) mMiniWeChatParams.getMiniThumb();
        } else if (mMiniWeChatParams.getMiniThumb() instanceof Integer) {
            bitmap = ((BitmapDrawable) Objects.requireNonNull(ContextCompat.getDrawable(mActivity, ((int) mMiniWeChatParams.getMiniThumb())))).getBitmap();
        } else if (mMiniWeChatParams.getMiniThumb() instanceof String) {
            GlideUtil.getUrlCacheBitmapForShareThumbnail(mActivity, mMiniWeChatParams.getMiniThumb().toString(), new GetUrlCacheBitmapListenerWithFail() {
                @Override
                public void loadBitmap(Bitmap resource) {
                    finalWeChatMini(mMiniWeChatParams, resource, mActivity);
                }

                @Override
                public void loadFail() {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.show("加载失败");
                        }
                    });
                }
            });
        } else {
            bitmap = ((BitmapDrawable) Objects.requireNonNull(ContextCompat.getDrawable(mActivity, R.mipmap.icon_base_placeholder))).getBitmap();
        }
        if (mMiniWeChatParams.getMiniThumb() instanceof String) {

        } else {
            finalWeChatMini(mMiniWeChatParams, bitmap, mActivity);
        }
    }


    /**
     * 分享短信文本
     */
    public void shareSmsText(String text, Activity mActivity) {
        if (mActivity == null) {
            ToastUtil.show("分享资源有误");
            return;
        }
        Uri smsToUri = Uri.parse("smsto:");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
        //短信内容
        sendIntent.putExtra("sms_body", text);
        sendIntent.setType("vnd.android-dir/mms-sms");
        mActivity.startActivity(sendIntent);
    }


    /**
     * 分享短信文本
     */
    public void shareSmsText(String number, String text, Activity mActivity) {
        if (mActivity == null) {
            ToastUtil.show("分享资源有误");
            return;
        }
        Uri smsToUri = Uri.parse("smsto:" + number);
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
        //短信内容
        sendIntent.putExtra("sms_body", text);
        sendIntent.setType("vnd.android-dir/mms-sms");
        mActivity.startActivity(sendIntent);
    }

    /**
     * 分享内容到手机系统的分享
     */
    public void shareToSystemText(String content, Activity mActivity) {
        if (mActivity == null) {
            ToastUtil.show("分享资源有误");
            return;
        }
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("text/plain"); //可以切换文案跟img
        localIntent.putExtra("android.intent.extra.SUBJECT", "分享");
        localIntent.putExtra("android.intent.extra.TEXT", content);
        mActivity.startActivity(Intent.createChooser(localIntent, "分享到"));
    }


    /**
     * 分享短信图片
     */
    public void shareSmsImage(Bitmap bitmap, Activity mActivity) {
        if (mActivity == null || bitmap == null) {
            ToastUtil.show("分享资源有误");
            return;
        }
        //由文件得到uri
//        File file = BitmapUtil.saveBitmapFile(bitmap);
//        Uri imageUri = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", file);
//        Intent shareIntent = new Intent();
//        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享到");
//        shareIntent.setAction(Intent.ACTION_SEND);
//        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
//        shareIntent.setType("image/*");
//        mActivity.startActivity(shareIntent);
    }

    /**
     * 企业微信分享文本
     */
    public void shareEnterpriseWechatText(Activity mActivity, String text) {
        if (mActivity == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra(Intent.EXTRA_TEXT, text);
        intent.setType("text/plain");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setPackage(Constant.WWEIXIN_PACKAGE);
        mActivity.startActivity(intent);
    }

    /**
     * 分享的类型：img、webpage、text、miniProgram
     *
     * @param type
     * @return
     */
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public String adapterUri(String path) {
        if (checkVersionValid() && checkAndroidNotBelowN()) {
            File file = new File(path);
            return getFileUri(App.instance.getBaseContext(), file);
        } else {
            return path;
        }
    }

    public boolean checkVersionValid() {
        return api.getWXAppSupportAPI() >= 0x27000D00;
    }

    public boolean checkAndroidNotBelowN() {
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N;
    }

    public String getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            return null;
        }

        Uri contentUri = FileProvider.getUriForFile(context, AppUtils.getAppPackageName() + ".provider", file);
        context.grantUriPermission("com.tencent.mm",
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return contentUri.toString();
    }
}
